package gameEngine.agents.Logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

import ui.flowManager.expirimentProperties.ExperimentProperties;
/**
 * abstract class for textual loggers
 * creates a file and expect text info
 * @author alon
 *
 */
public abstract class textLogger implements ILogger {

	Logger log = Logger.getLogger(this.getClass());
	
	File file;
	int counter=0;
	String str=new String();
	FileWriter fstream;
	BufferedWriter out;
	final private int TURN_NUM=10;
	
	/**
	 * Constructor creates a file with name of pattern:
	 * Game+ID_log_creation time stamp. file extansion
	 * for example:
	 * Game2_log_111111.csv 
	 * @param extension file type
	 * @param gameNum gmae ID
	 */
	public textLogger(String extension,int gameNum){
		String dirName="C:\\Users\\alon\\Desktop\\adaptiveagentsbiu\\AdaptiveAgents\\Result\\"+ExperimentProperties.getExperimentName();
		if(!new File(dirName).exists()){
			boolean success = new File (dirName).mkdir();
			if(success){
				log.debug("created directory "+dirName);
				file=new File(dirName,"Game"+gameNum+"_log_"+System.currentTimeMillis()+"."+extension);	
			}else{
				log.debug("directory not created writing to relative path");
				file=new File("Game"+gameNum+"_log_"+System.currentTimeMillis()+"."+extension);	
			}
		}else{	
			log.debug(dirName+" exists write to it");
			file=new File(dirName,"Game"+gameNum+"_log_"+System.currentTimeMillis()+"."+extension);	
		}
		try {
			fstream = new FileWriter(file);
		} catch (IOException e) {
			log.debug("failed to init file stream\n"+ e.getMessage());
		}
		out = new BufferedWriter(fstream);		
	}
	/**
	 * gets info as string and adds to a buffer
	 * each 10 turns write to file
	 */
	public void log(String info) {
		log.debug("got new message :"+info);
		str+=info+"\n";
		if(counter>TURN_NUM){
			counter=0;
			try{
				// Create file 
				out.write(str);
				log.debug("done writing a buffer");
			}catch (Exception e){//Catch exception if any
				log.debug("writing log failed\n"+ e.getMessage());
			}
			str="";
		}else{
			counter++;
		}
	}
	
	public abstract void flush();

}
